const express = require('express');
const router = express.Router();
const utility = require("utility")
// const db = require("../db");
const fn = require("../db_sql");

const jwt = require("jsonwebtoken")


//    添加： /addcates  post 
router.post("/reguser", async function (req, res) {
    // 1.获取数据：曾经 req.on("data") 
    //   req.body

    req.body.password = utility.md5(req.body.password)
    // 2.把数据添加数据库

    try {
        await fn(`insert into user set ?`, req.body)
        res.send({
            "status": 0,
            "message": "注册成功！",
        });
    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "注册失败！",
        });
    }

});

// 登录
router.post("/login", async function (req, res) {
    req.body.password = utility.md5(req.body.password)
    try {
        let arr = await fn("select * from user where username=? and password=?", [req.body.username, req.body.password])
        let token = 'Bearer ' + jwt.sign({
            userId: arr[0].id
        }, 'token130', {
            expiresIn: '2h'
        })
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 0,
            "message": "登录成功！",
            "token": token
        });

    } catch (error) {
        res.send({ //无需设置请求头 ，和转换为JSON
            "status": 1,
            "message": "用户名或密码错误！",
        });
    }
})

// 固定4：导出模块。主app.js内部需要这个JS文件的内容！
module.exports = router;